<template>
  <el-row>
    <el-row class="pading-20 my-border my-bg">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>测试用例管理</el-breadcrumb-item>
        <el-breadcrumb-item>测试执行用例</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>

    <el-row>
      <div class="operate">
        <el-button size="small" type="primary" icon="el-icon-delete" @click="clear">清空</el-button>
        <el-input ref="queryProjectText" v-model="queryTaskText" size="small" placeholder="项目名称查询"
                  style="width: 150px;margin-left: 20px;margin-right: 10px"></el-input>
        <el-button size="small" type="primary" icon="el-icon-search" @click="query">查询</el-button>
        <el-tag style="margin-left: 50px">注：研发只能看到自己所属的项目，测试可以看到全局项目</el-tag>

      </div>
    </el-row>

    <el-row style="margin-top: 20px;width: 100%">
      <vxe-table  border resizable show-overflow ref="xTable" row-id="caseId" :data="tableData"
                 :edit-config="{trigger: 'dblclick', mode: 'row'}"
                 :menu-config="tableMenu"
                  @menu-click="contextMenuClickEvent"
                 :tree-config="{transform: true,expandAll: false, reserve: true,rowField: 'caseId', parentField: 'parentId'
                 ,lazy: true, hasChild: 'hasChildren', loadMethod: loadChildrenMethod}"
                 @toggle-tree-expand="toggleExpandChangeEvent">

        <vxe-column field="caseName" title="用例节点树" min-width="300px" tree-node :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.caseName" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="casePriority" title="优先级" min-width="80px">
          <template #default="{ row }">
            <span v-if="row.casePriority!=''"> <el-tag class="bold" :type="formatLevelClass(row.casePriority)">P{{
                row.casePriority
              }}</el-tag></span>
          </template>
        </vxe-column>
        <vxe-column field="rdRun" title="研发自测人" min-width="100px"></vxe-column>
        <vxe-column field="rdRunResult" title="自测结果" min-width="80px">
          <template #default="{ row }">
            <span v-if="row.rdRunResult!=''"> <el-tag class="bold" :type="formatResultClass(row.rdRunResult)">{{row.rdRunResult}}</el-tag></span>
          </template>
        </vxe-column>
        <vxe-column field="rdRunTime" title="自测执行时间" min-width="170px"></vxe-column>
        <vxe-column field="testerRun" title="测试执行人" min-width="100px"></vxe-column>
        <vxe-column field="testerRunResult" title="测试结果" min-width="80px">
          <template #default="{ row }">
            <span v-if="row.testerRunResult!=''"> <el-tag class="bold" :type="formatResultClass(row.testerRunResult)">{{row.testerRunResult}}</el-tag></span>
          </template>
        </vxe-column>
        <vxe-column field="testerRunTime" title="测试执行时间" min-width="170px"></vxe-column>
        <vxe-column title="操作" width="400">
          <template #default="{ row }">
            <vxe-button v-per="'caseTree_save'" type="text" status="success" icon="fa vxe-icon--check" @click="saveRow(row)">保存</vxe-button>

            <vxe-button v-per="'caseTree_run'"   transfer placement="bottom" v-if="!row.hasChildren && row.parentId!='null'" >
              <template #default >执行用例</template>
              <template #dropdowns >
                <vxe-button  type="text" status="success" @click="runCase(row,'通过')">执行成功</vxe-button>
                <vxe-button  type="text" status="danger" @click="runCase(row,'失败')">执行失败</vxe-button>
              </template>
            </vxe-button>

            <vxe-button v-per="'caseTree_insert'" type="text" status="primary" icon="fa vxe-icon--plus" @click="insertRow(row, 'bottom')">插入
            </vxe-button>
            <vxe-button v-per="'caseTree_del'" type="text" status="danger" icon="fa vxe-icon--close" @click="removeRow(row)">移除</vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-row>
    <el-pagination style="margin-top:30px;float: left"
                   background
                   layout="prev, pager, next"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="currentPage"
                   :page-size="pageSize"
                   :page-count="pageCount">
    </el-pagination>

  </el-row>
</template>

<script>

import templateData from "../../../static/templateData"
import {generateMixed} from "../../utils";
import {post} from "../../../src/utils/httpUtils.js"
import { VXETable, VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table'

export default {
  name: "caseManagement",


  data() {
    return {
      tableTestCaseTitle: templateData.tableTestCaseTitle,
      queryTaskText: "",
      tableData: [],
      childData:[],
      pageSize:5,
      pageCount:0,
      currentPage:1,
      parentNode:{},
      tableMenu: {
        body: {
          options: [
            [
              {code: 'insert', name: '插入下级', disabled: false},
              {code: 'run-pass', name: '执行用例-通过', disabled: false},
              {code: 'run-fail', name: '执行用例-失败', disabled: false},
              {code: 'remove', name: '删除', disabled: false}
            ]
          ]
        }
      }
    }

  },
  methods: {


    formatLevelClass(value) {
      if (value == '1') {
        return 'danger'
      }
    },

    formatResultClass(value) {
      if (value == "成功") {
        return "success"
      }else if (value == "失败") {
        return "danger"
      }
    },


    toggleExpandChangeEvent({row, expanded}) {
    },
    handleSizeChange(size) {
      this.currentPage = 1;//每次改变每页多少条都会重置当前页码为1
      this.pageSize = size;
      this.getData(this.currentPage, this.pageSize, this.queryTaskText)
    },
    handleCurrentChange(size) {
      this.currentPage = size;
      this.getData(this.currentPage, this.pageSize, this.queryTaskText)
    },

    query() {
      this.getData(1, this.pageSize, this.queryTaskText)
    },
    clear() {
      this.queryTaskText = "";
      this.getData(1, this.pageSize, this.queryTaskText)
    },


    loadChildrenMethod({ row }) {
      // 异步加载子节点
      return new Promise(resolve => {
        this.getChild(row.caseId)
        setTimeout(() => {
          resolve(this.childData)
        }, 500)
      })
    },

    getChild(caseId){
      let pageObject = {}
      pageObject['data']=caseId
      post('/api/case/queryChild',JSON.stringify(pageObject)).then((response)=> {
        this.childData= response.data;
      })
    },


    getData(currPage,pageSize,queryTaskText) {
      let pageObject={}
      pageObject['offset']=currPage
      pageObject['limit']=pageSize
      pageObject['data']=queryTaskText
      post('/api/case/queryAll',JSON.stringify(pageObject)).then((response)=> {
        this.tableData = response.data.rows;
        this.pageCount = Math.ceil(response.data.total / this.pageSize);
      })
    },

    async removeRow(row) {
      this.$confirm('此操作将永久删除该用例和其下级用例, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let pageObject = {}
        pageObject['data'] = row
        post('/api/case/removeCase', JSON.stringify(pageObject)).then((response) => {
          this.$refs.xTable.remove(row)
          this.$message({type: 'success', message: '删除成功!'});
        })
      })
    },


    async runCase(row, flag) {
      let pageObject = {}, data = {}
      data['result'] = flag
      data['operater'] = localStorage.getItem('nick_name')
      data['id'] = row.id
      pageObject['data'] = data
      post('/api/case/runCase', JSON.stringify(pageObject)).then((response) => {
        this.$message({message: '执行成功', type: 'success'});
        this.queryParent(this.tableData,row.parentId);
        this.$refs.xTable.reloadTreeExpand(this.parentNode)
      })
    },

    contextMenuClickEvent({menu,row, column}) {
      switch (menu.code) {
        case "run-pass":
          if(!row.hasChildren && row.parentId!='null'){
            this.runCase(row, "通过")
          }else{
            this.$message({type: 'warning', message: '当前节点非实际用例节点，无法执行!'});
          }
          break
        case "run-fail":
          if(!row.hasChildren && row.parentId!='null'){
            this.runCase(row, "失败")
          }else{
            this.$message({type: 'warning', message: '当前节点非实际用例节点，无法执行!'});
          }
          break
        case "insert":
          this.insertRow(row,"bottom")
          break
        case "remove":
          if(row.parentId!='null'){
            this.removeRow(row)
          }else{
            this.$message({type: 'warning', message: '当前节点是顶层节点，无法删除!'});
          }
          break
      }


    },


    async queryParent(tableData,parentId){
      let that=this;
      tableData.forEach(function (item){
        if(item.caseId==parentId){
            that.parentNode=item
        }else{
          if(item.children!=null && item.children.length>0){
            item.children.forEach(function (itm){
              that.queryParent(item.children,parentId)
            })
          }
        }
      })
    },


    async saveRow(row) {
      let pageObject = {}
      pageObject['data'] = row
      post('/api/case/saveCase', JSON.stringify(pageObject)).then((response) => {
        this.$message({message: '保存成功', type: 'success'});
        this.getData(this.currentPage, this.pageSize, "")
      })

    },

    async insertRow(currRow, locat) {
      const $table = this.$refs.xTable
      if (locat === 'bottom') {
        const record = {
          caseName: '新用例节点，请编辑',
          caseId: generateMixed(12),
          parentId: currRow.caseId, // 需要指定父节点，自动插入该节点中
          casePriority: "",
          caseProgress: "",
          taskId: currRow.taskId,
          template: currRow.template,
          theme: currRow.theme,
          hasChildren:false
        }
        const {row: newRow} = await $table.insertAt(record, -1)
        await $table.setTreeExpand(currRow, true) // 将父节点展开
        await $table.setActiveRow(newRow) // 插入子节点
      }
    },
  },

  created() {
    this.getData(1, this.pageSize, "")
  }
}

</script>

<style scoped>
.my-border {
  border-radius: 3px;
  border: 1px solid #ebebeb;
}


html, body {
  background-color: #fafafa;
}

.my-bg {
  background-color: #fff
}

.pading-20 {
  padding: 20px;
}

.operate {
  float: left;
  margin-left: 20px;
  margin-top: 30px;
}

.bold {
  font-weight: bold;
}

.text-left {
  text-align: left;
}

i {
  cursor: pointer
}

.vxe-button.type--button:not(.is--circle){
  border: none;
  color: #409eff;
}

</style>
